<template>
  <el-dialog
    :title="state.title"
    @close="handleClose"
    width="1200"
    v-model="state.visible"
    :before-close="beforeClose"
    :loading="state.loading"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <div>
      <yt-crud
        v-bind="options"
        ref="crudRef"
        @onLoad="getData"
        :fun-props="{
          hide: true,
        }"
        :table-props="{
          index: false,
          selection: true,
          delBtn: true,
          pageHide: true,
          viewBtn: false,
          editBtn: false,
          menu: false,
        }"
        :loading="state.loading"
        :total="state.total"
        v-model:page="state.page"
        v-model:query="state.query"
        @openBeforeFun="openBeforeFun"
        @change="onChange"
      >
        <template #rightToolbar></template>
        <template #enableTime="scope:any">
          <span>{{ parseTime(scope.row.enableTime, '{y}-{m}-{d}') }}</span>
        </template>
        <template #expireTime="scope:any">
          <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
        </template>
        <template #state="scope:any">
          <DictTag :options="LedgerStateEnum" :value="scope.row.state" />
        </template>

        <template #type="scope:any">
          <DictTag :options="LedgerTypeEnum" :value="scope.row.type" />
        </template>
        <template #name="scope:any">
          <span v-if="scope.row.type == 'Platform'">-</span>
          <span v-if="scope.row.type == 'Tenant'">{{scope.row.tenantName}}</span>
          <span v-if="scope.row.type == 'Agent'">{{scope.row.agentName}}</span>
          <span v-if="scope.row.type == 'Dealer'">{{scope.row.dealerName}}</span>
        </template>

        <template #menuSlot></template>
      </yt-crud>
    </div>

    <template #footer>
      <el-button @click="handleClose" :loading="form.loading">{{t('crud.cancelText')}}</el-button>
      <el-popconfirm :title="t('business.ledgerSettleDealer.tooltip.settleConfirm')" @confirm="handleSubmit">
        <template #reference>
          <el-button type="primary" :loading="form.loading">{{t('crud.confirmText')}}</el-button>
        </template>
      </el-popconfirm>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

import YtCrud from '@/components/common/yt-crud.vue'
import { ledgerList } from '@/api/business/ledger'
import {ComponentInternalInstance} from 'vue'
import {parseTime} from '@/utils/ruoyi'
import {useI18n} from 'vue-i18n'
import {ledgerSettleAdd} from '@/api/business/ledgerSettle'
import {optionSelect as dealerOptionSelect} from '@/api/system/dealer'
import {optionSelect as stationOptionSelect} from '@/api/business/station'
import {IColumn} from '@/components/common/types/tableCommon'
const { t } = useI18n()



const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { LedgerStateEnum, LedgerTypeEnum } = toRefs<any>(proxy?.useEnum('ledger_state_enum', 'ledger_type_enum'))
const emits = defineEmits(['success'])


const form = reactive({
  loading: false,
})

const state = reactive({
  visible: false,
  loading: false,
  recharge: {},
  title: t('business.ledgerSettleDealer.action.add'),
  page: {
    pageSize: 99999999,
    pageNum: 1,
  },
  total: 0,
  query: {},
})

const dealers = ref<any[]>([])
const loadDealers = () => {
  dealerOptionSelect({
    ...state.page
  })
  .then((res) => {
    dealers.value = res.data
  })
}

const stations = ref<any[]>([])
const loadStations = () => {
  stationOptionSelect({
    ...state.page
  })
    .then((res) => {
      stations.value = res.data
    })
}

const column:IColumn[] = [
  {
    label: t('business.ledger.type'),
    key: 'type',
    align: 'center',
    type: 'select',
    search: true,
    componentProps: {
      options: LedgerTypeEnum,
      style: {
        width: '120px'
      }
    },
    slot: true,
  },
  {
    label: t('business.ledger.name'),
    key: 'name',
    type: 'string',
    search: true,
    formHide: false,
    searchLabelWidth: 120,
    slot: true,
    align: 'center',
    colSpan: 22,
  },
  {
    label: t('business.ledger.orderTranId'),
    key: 'orderTranId',
    search: true,
    slot: false,
  },
  {
    label: t('business.ledger.stationId'),
    key: 'stationId',
    type: 'i18nSelect',
    slot: false,
    search: false,
    componentProps: {
      valueAlias: 'id',
      labelAlias: 'name',
      options: stations,
    },
  },
  {
    label: t('business.ledger.chargerDn'),
    key: 'chargerDn',
    search: false,
    align: 'center',
    slot: false,
  },
  {
    label: t('business.ledger.totalAmount'),
    key: 'totalAmount',
    search: false,
    align: 'center',
    slot: false,
  },
  {
    label: t('business.ledger.settledServiceAmount'),
    key: 'settledServiceAmount',
    search: false,
    align: 'center',
    slot: false,
  },
  {
    label: t('business.ledger.amount'),
    key: 'amount',
    search: false,
    align: 'center',
    slot: false,
  },
  {
    label: t('business.ledger.state'),
    key: 'state',
    search: false,
    align: 'center',
    slot: true,
  },
]

const openDialog = () => {
  loadDealers()
  loadStations()
  state.query = {}
  state.visible = true
}

const handleClose = () => {
  state.visible = false
}


const beforeClose = (done: () => void) => {
  done()
}
defineExpose({
  openDialog,
})

const crudRef = ref()
const data = ref<any[]>([])
const getData = () => {
  state.loading = true
  ledgerList({
    ...state.page,
    ...state.query,
    ...{ state: LedgerStateEnum.value.Pending.value }
  })
    .then((res) => {
      data.value = res.data.rows
      state.total = res.data.total
    })
    .finally(() => {
      state.loading = false
    })
}

const openBeforeFun = ({ type}) => {
  if (type === 'add') { /* empty */ } else if (type === 'update') { /* empty */ }
}

const multipleSelection = ref<any[]>([])

const onChange = (data) => {
  multipleSelection.value = data
}

const handleSubmit = () => {
  let ledgerIds = multipleSelection.value.map(element => element.id)
  if(!ledgerIds ||ledgerIds.length == 0) {
    ElMessage.warning(t('business.ledgerSettleDealer.tooltip.selectionEmpty'))
    return
  }

  form.loading = true
  let params = {
    ledgerIds: multipleSelection.value.map(element => element.id),
  }
  ledgerSettleAdd(params).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    handleClose()
    emits('success', data)
  }).finally(() => (
    form.loading = false
  ))
}

const options = reactive({
  ref: 'crudRef',
  data,
  column,
})
</script>
